package com.xyx.yfy_site_msg.system.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyx.yfy_site_msg.system.entity.YfyMenu;
import com.xyx.yfy_site_msg.system.entity.YfyUser;
import com.xyx.yfy_site_msg.system.service.YfyMenuService;
import com.xyx.yfy_site_msg.system.service.YfyUserService;
import com.xyx.yfy_site_msg.system.utils.ActiverUser;
import com.xyx.yfy_site_msg.system.utils.Constast;
import com.xyx.yfy_site_msg.system.vo.YfyMenuVo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.Factory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.List;


public class UserRealm extends AuthorizingRealm {
	private static final Integer USER_TYPE = 0;
	@Autowired
	@Lazy // 确保切面解析完成 使用的时候加载
	private YfyUserService userService;

	@Autowired
	@Lazy
	private YfyMenuService menuService;

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return this.getClass().getSimpleName();
	}
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		QueryWrapper<YfyUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username",token.getPrincipal().toString());
		YfyUser user = userService.getOne(queryWrapper);
		if (null!=user){
			ActiverUser activerUser = new ActiverUser();
			activerUser.setUser(user);
			ByteSource credentialsSalt  = ByteSource.Util.bytes(user.getSalt());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser,user.getPassword(),credentialsSalt,this.getName());
			return info;
		}
		return null;
	}

	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		ActiverUser activerUser = (ActiverUser) principals.getPrimaryPrincipal();
		if (activerUser!=null){
			Integer usertype = activerUser.getUser().getUsertype();
			if (usertype== USER_TYPE) {
				List<String> lists=this.menuService.loadAllPermissionByUsertype(USER_TYPE);
				for (String  list: lists){
					simpleAuthorizationInfo.addStringPermission(list);
				}
				return simpleAuthorizationInfo;
			}
			simpleAuthorizationInfo.addStringPermission("*:*");
			return simpleAuthorizationInfo;
		}
		return null;
	}
}